﻿using System.Linq;
using System.Threading.Tasks;
using iSlideTools.LocalServer.Data;
using iSlideTools.LocalServer.Models;
using iSlideTools.LocalServer.Options;
using iSlideTools.LocalServer.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace iSlideTools.LocalServer.Controllers
{
    [Route("api/[controller]")]
    public class VerifyMacAddressController : Controller
    {
        private readonly DataContext _dataContext;
        private readonly TokenServer _tokenServer;

        public VerifyMacAddressController(IOptions<JwtIssuerOptions> jwtOptions,
            IOptions<SecretKeyOptions> secretKeyOptions, DataContext dataContext)
        {
            _tokenServer = new TokenServer(jwtOptions.Value, secretKeyOptions.Value);
            _dataContext = dataContext;
        }

        // GET: api/values
        [HttpPost("GenerateToken")]
        [AllowAnonymous]
        public async Task<IActionResult> GenerateToken([FromBody] ValidApp app)
        {
            var identity = await _tokenServer.AppValidate(app);
            if (identity == null)
                return BadRequest("无效的身份信息");

            var json = await _tokenServer.GenerateToken(identity);
            return new OkObjectResult(json);
        }

        [HttpGet("Verify")]
        [Authorize(Policy = AuthorizationInfo.LoginUserPolicy)]
        public IActionResult Verify(string macAddress)
        {
            if (string.IsNullOrEmpty(macAddress))
                return new BadRequestObjectResult("mac地址不能为空！");
            var existMacAddress = _dataContext.ValidMacAddresses.FirstOrDefault(mac => mac.MacAddress == macAddress);
            if (existMacAddress != null)
                return new OkObjectResult("true");
            return new OkObjectResult("false");
        }
    }
}